<?php

namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\CommentModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\MyNoticeModel;
use app\models\MyNoticeObjectModel;
use app\models\StudentModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\ParentInformationModel;
use app\models\UserModel;
use think\Db;

class CommentService extends BaseService
{
    /**
     * User: wufeng
     * Date: 2020/03/02.
     *
     * @param $params
     *
     * @return mixed
     */
    public function classCommentWeekLists($params)
    {
        try {
            // c_type 2 老师点评学生;是否答案解析 默认为0未点评；1已点评
            $student_ids = (new StudentSubjectInfosClassModel())
                ->where(['campus_id' => ['in', xcxapi_get_current_campus_id()]])
                ->whereTime('class_date', 'week')
                ->column('student_id');
            //总学员人数
            $student_total_num = \count(array_unique($student_ids));
            $ids = (new GradesDetailsListsModel())
                ->where(['campus_id' => ['in', xcxapi_get_current_campus_id()]])
                ->whereTime('class_date', 'week')
                ->column('id');

            //总作业学员分数
            $work_student_total_fraction = (new CommentModel())->where(['c_type' => 1, 'cmdl_id' => ['in', implode(',', $ids)]])->sum('student_scoring');
            //学生评分
			if($student_total_num == 0){
				$this->data['total']['fraction'] = 0;
			}else{
				$this->data['total']['fraction'] = $work_student_total_fraction / $student_total_num;	
			}

            //学生评价数
            $this->data['total']['student_evaluate_num'] = (new CommentModel())->where(['c_type' => 1, 'cmdl_id' => ['in', implode(',', $ids)]])->count();
            //老师评价数
            $this->data['total']['teacher_evaluate_num'] = (new CommentModel())->where(['c_type' => 2, 'cmdl_id' => ['in', implode(',', $ids)]])->count();
            //评价总数
            $evaluate_num = (new CommentModel())->where(['cmdl_id' => ['in', implode(',', $ids)]])->count();

            if (0 === (int) $evaluate_num) {
                //学生评价率
                $this->data['total']['student_evaluate_rate'] = 0;
                //老师评价率
                $this->data['total']['teacher_evaluate_rate'] = 0;
            } else {
                //学生评价率
                $this->data['total']['student_evaluate_rate'] = $this->data['total']['student_evaluate_num'] / $evaluate_num;
                //老师评价率
                $this->data['total']['teacher_evaluate_rate'] = $this->data['total']['teacher_evaluate_num'] / $evaluate_num;
            }

            $where = [];
            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            $where['status'] = 1;
            $this->data['lists'] = (new GradesDetailsModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data['lists'] as &$comment) {
                //班课类型
                $comment['course_type'] = (new CourseModel())->get(['id' => $comment['course_id']])['course_type'];
                $comment['course_type_text'] = (new DictionaryModel())->get(['id' => $comment['course_type']])['name'];

                //待评价课节
                $comment['stay_appraise_comment'] = (new GradesDetailsListsModel())->where(['class_manage_id' => $comment['id'], 'is_comment' => 0])->count();

                $comment['gradesDetailsLists'] = (new GradesDetailsListsModel())
                    ->where(['class_manage_id' => $comment['id']])
                    ->select()
					->toArray();
                $i = 0;
                foreach ($comment['gradesDetailsLists'] as &$list) {
                    $i = $i + 1;
                    $list['class_day'] = '第'.$i.'节';
                    $list['class_datetime'] = $list['class_date'].' '.$list['class_subject_start'].'-'.$list['class_subject_end'];
                    // c_type 2 老师点评学生;是否答案解析 默认为0未点评；1已点评
                    $teacher_count = (new CommentModel())->where(['cmdl_id' => $list['id'], 'c_type' => 2, 'status' => 0])->count();
                    // c_type 1 学生点评老师;是否答案解析 默认为0未点评；1已点评
                    $student_count = (new CommentModel())->where(['cmdl_id' => $list['id'], 'c_type' => 1, 'status' => 0])->count();
                    $list['difference'] = $student_count.'/'.$teacher_count;
                }
            }

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/05.
     *
     * @param $params
     *
     * @return array
     */
    public function classCommentAllLists($params)
    {
        try {
            // c_type 2 老师点评学生;是否答案解析 默认为0未点评；1已点评
            $student_ids = (new StudentSubjectInfosClassModel())
                ->where(['campus_id' => ['in', xcxapi_get_current_campus_id()]])
                ->column('student_id');
            //总学员人数
            $student_total_num = \count(array_unique($student_ids));
            $ids = (new GradesDetailsListsModel())
                ->where(['campus_id' => ['in', xcxapi_get_current_campus_id()]])
                ->column('id');
            //总作业学员分数
            $work_student_total_fraction = (new CommentModel())->where(['c_type' => 1, 'cmdl_id' => ['in', implode(',', $ids)]])->sum('student_scoring');
            //学生评分
			if($student_total_num == 0){
				$this->data['total']['fraction'] = 0;
			}else{
				$this->data['total']['fraction'] = $work_student_total_fraction / ($student_total_num * 5);
			}
            //学生评价数
            $this->data['total']['student_evaluate_num'] = (new CommentModel())->where(['c_type' => 1, 'cmdl_id' => ['in', implode(',', $ids)]])->count();
            //老师评价数
            $this->data['total']['teacher_evaluate_num'] = (new CommentModel())->where(['c_type' => 2, 'cmdl_id' => ['in', implode(',', $ids)]])->count();
            //评价总数
            $evaluate_num = (new CommentModel())->where(['cmdl_id' => ['in', implode(',', $ids)]])->count();

            if (0 === (int) $evaluate_num) {
                //学生评价率
                $this->data['total']['student_evaluate_rate'] = 0;
                //老师评价率
                $this->data['total']['teacher_evaluate_rate'] = 0;
            } else {
                //学生评价率
                $this->data['total']['student_evaluate_rate'] = $this->data['total']['student_evaluate_num'] / $evaluate_num;
                //老师评价率
                $this->data['total']['teacher_evaluate_rate'] = $this->data['total']['teacher_evaluate_num'] / $evaluate_num;
            }

            $where = [];
            $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            $where['graduation_status'] = 0;
            $this->data['lists'] = (new GradesDetailsModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data['lists'] as &$comment) {
                //班课类型
                $comment['course_type'] = CourseModel::get(['id' => $comment['course_id']])['course_type'];
                $comment['course_type_text'] = DictionaryModel::get(['id' => $comment['course_type']])['name'];

                //待评价课节
                $comment['stay_appraise_comment'] = (new GradesDetailsListsModel())->where(['class_manage_id' => $comment['id'], 'is_comment' => 0])->count();

                $comment['gradesDetailsLists'] = (new GradesDetailsListsModel())
                    ->where(['class_manage_id' => $comment['id']])
                    ->select();
                $i = 0;
                foreach ($comment['gradesDetailsLists'] as &$list) {
                    $i = $i + 1;
                    $list['class_day'] = '第'.$i.'节';
                    $list['class_datetime'] = $list['class_date'].' '.$list['class_subject_start'].'-'.$list['class_subject_end'];
                    // c_type 2 老师点评学生;是否答案解析 默认为0未点评；1已点评
                    $teacher_count = (new CommentModel())->where(['cmdl_id' => $list['id'], 'c_type' => 2, 'status' => 0])->count();
                    // c_type 1 学生点评老师;是否答案解析 默认为0未点评；1已点评
                    $student_count = (new CommentModel())->where(['cmdl_id' => $list['id'], 'c_type' => 1, 'status' => 0])->count();
                    $list['difference'] = $student_count.'/'.$teacher_count;
                }
            }

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/03.
     *
     * @param $params
     *
     * @return array
     */
    public function classDayCommentLists($params)
    {
        try {
            $where = [];
            $where['class_manage_details_id'] = $params['id'];
            $gradesDetailsLists = (new GradesDetailsListsModel())->get($params['id']);
            //班课类型
            $this->data['detail']['course_type'] = CourseModel::get(['id' => $gradesDetailsLists['course_id']])['course_type'];
            $this->data['detail']['course_type_text'] = DictionaryModel::get(['id' => $this->data['detail']['course_type']])['name'];
            $this->data['detail']['class_subject_start'] = $gradesDetailsLists['class_subject_start'];
            $this->data['detail']['class_subject_end'] = $gradesDetailsLists['class_subject_end'];
            $this->data['detail']['class_date'] = $gradesDetailsLists['class_date'];
            $this->data['detail']['weekday'] = $gradesDetailsLists['weekday'];
            $this->data['detail']['headmaster'] = $gradesDetailsLists['headmaster'];
            $this->data['detail']['teacher'] = $gradesDetailsLists['teacher'];
            $this->data['detail']['assistant'] = $gradesDetailsLists['assistant'];
            $this->data['detail']['class_room'] = $gradesDetailsLists['class_room'];
            $this->data['detail']['course_name'] = CourseModel::get(['id' => $gradesDetailsLists['course_id']])['course_name'];
            $ids = (new GradesDetailsListsModel())->where(['class_manage_id' => $gradesDetailsLists['class_manage_id']])->order('class_date asc')->column('id');
            $i = array_search($params['id'], $ids);
            if (($i - 1) < 0) {
                $this->data['detail']['up_day'] = -1;
            } else {
                $this->data['detail']['up_day'] = $ids[$i - 1];
            }
            if (($i + 1) >= \count($ids)) {
                $this->data['detail']['down_day'] = -1;
            } else {
                $this->data['detail']['down_day'] = $ids[$i + 1];
            }
            $j = $i + 1;
            $this->data['detail']['class_day'] = '第'.$j.'节';
            $this->data['detail']['status'] = $gradesDetailsLists['status'];
            //学生总人数
            $this->data['total']['number'] = (new StudentSubjectInfosClassModel())->where($where)->count();
            //平均分
            $this->data['total']['student_average'] = (new CommentModel())->where(['c_type' => 1, 'cmdl_id' => $params['id']])->sum('student_scoring');
            $this->data['total']['teacher_average'] = (new CommentModel())->where(['c_type' => 2, 'cmdl_id' => $params['id']])->sum('teacher_scoring');

            $this->data['lists'] = (new StudentSubjectInfosClassModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data['lists'] as &$list) {
                //考勤，0为未考勤，1为考勤
                if (1 === (int) $list['attendance']) {
                    $list['attendance_text'] = '已签到';
                } elseif (2 === (int) $list['attendance']) {
                    $list['attendance_text'] = '未签到';
                }
                $student_img = (new StudentModel())->get($list['student_id'])['student_img'];
                $list['student_img'] = $student_img ? $student_img : '/picture.jpg';
                //点评类型：1学生点评老师 2老师点评学生
                $list['student_comment_status'] = (new CommentModel())->get(['c_type' => 1, 'cmdl_id' => $list['class_manage_details_id'], 'student_id' => $list['student_id']])['status'];
                if (null === $list['student_comment_status']) {
                    $list['student_comment_status'] = 0;
                }
                $list['teacher_comment_status'] = (new CommentModel())->get(['c_type' => 2, 'cmdl_id' => $list['class_manage_details_id'], 'student_id' => $list['student_id']])['status'];
                if (null === $list['teacher_comment_status']) {
                    $list['teacher_comment_status'] = 0;
                }
            }
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/05.
     *
     * @param $params
     *
     * @return array
     */
    public function classDayCommentDetail($params)
    {
        try {
            $this->data['student'] = (new CommentModel())->get(['c_type' => 1, 'cmdl_id' => $params['cmdl_id'], 'student_id' => $params['student_id']]);
            if ($this->data['student']) {
                $this->data['student']['student_name'] = (new StudentModel())->get($params['student_id'])['student_name'];
            }
            $this->data['teacher'] = (new CommentModel())->get(['c_type' => 2, 'cmdl_id' => $params['cmdl_id'], 'student_id' => $params['student_id']]);
            if ($this->data['teacher']) {
                $this->data['teacher']['teacher_name'] = (new UserModel())->get($this->data['teacher']['teacher_id'])['name'];
            }
            $where = [];
            $where['class_manage_details_id'] = $params['cmdl_id'];
            $gradesDetailsLists = (new GradesDetailsListsModel())->get($params['cmdl_id']);
            //班课类型
            $this->data['detail']['course_type'] = CourseModel::get(['id' => $gradesDetailsLists['course_id']])['course_type'];
            $this->data['detail']['course_type_text'] = DictionaryModel::get(['id' => $this->data['detail']['course_type']])['name'];
            $this->data['detail']['class_subject_start'] = $gradesDetailsLists['class_subject_start'];
            $this->data['detail']['class_subject_end'] = $gradesDetailsLists['class_subject_end'];
            $this->data['detail']['class_date'] = $gradesDetailsLists['class_date'];
            $this->data['detail']['weekday'] = $gradesDetailsLists['weekday'];
            $this->data['detail']['headmaster'] = $gradesDetailsLists['headmaster'];
            $this->data['detail']['teacher'] = $gradesDetailsLists['teacher'];
            $this->data['detail']['assistant'] = $gradesDetailsLists['assistant'];
            $this->data['detail']['class_room'] = $gradesDetailsLists['class_room'];
            $this->data['detail']['course_name'] = CourseModel::get(['id' => $gradesDetailsLists['course_id']])['course_name'];
            $ids = (new GradesDetailsListsModel())->where(['class_manage_id' => $gradesDetailsLists['class_manage_id']])->order('class_date asc')->column('id');
            $i = array_search($params['cmdl_id'], $ids);
            if (($i - 1) < 0) {
                $this->data['detail']['up_day'] = -1;
            } else {
                $this->data['detail']['up_day'] = $ids[$i - 1];
            }
            if (($i + 1) >= \count($ids)) {
                $this->data['detail']['down_day'] = -1;
            } else {
                $this->data['detail']['down_day'] = $ids[$i + 1];
            }
            $j = $i + 1;
            $this->data['detail']['class_day'] = '第'.$j.'节';
            $this->data['detail']['status'] = $gradesDetailsLists['status'];
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 课节点评
     * User: wufeng
     * Date: 2020/03/05.
     *
     * @param $params
     *
     * @return array
     */
    public function classDayComment($params)
    {
        try {
            $data = [];
            $data['cmdl_id'] = $params['cmdl_id'];
			//通过课节找出老师ID 默认都是任课老师点评 如果任课老师未创建账号则是当前登录者点评
			$grades_id = GradesDetailsListsModel::get(['id' => $params['cmdl_id']])['class_manage_id'];
			$grades_res = GradesDetailsModel::get(['id' => $grades_id]);
			$teacher_id = $grades_res['teacher_id'];
			$teacher_user_id = UserModel::get(['teacher_id' => $teacher_id])['id'];
			if(isset($teacher_user_id) && '' !== $teacher_user_id && null !== $teacher_user_id){
				$data['teacher_id'] = $teacher_user_id;
			}else{
				$data['teacher_id'] = xcxapi_get_current_user_id();
			}
            $data['student_id'] = $params['student_id'];
		  //$data['teacher_id'] = xcxapi_get_current_user_id();
            $data['teacher_scoring'] = $params['teacher_scoring'];
            $data['comment_time'] = date('Y-m-d H:i:s');
            $data['content'] = $params['content'];
            $data['audio'] = $params['audio'];
            $data['audio_duration'] = $params['audio_duration'];
            $data['video'] = $params['video'];
            $data['picture'] = $params['picture'];
            $data['c_type'] = 2;
            $data['status'] = 1;
			$status_comment = false;
            if (isset($params['id']) && '' !== $params['id'] && null !== $params['id']) {
				$status_comment = false;
                (new CommentModel())->save($data, ['id' => $params['id']]);
            } else {
				$status_comment = true;
                (new CommentModel())->save($data);			
            }
			
				//发布点评通知
				$course_name = CourseModel::get(['id' => $grades_res['course_id']])['course_name'];
				$data_notice = [];
				$data_notice['notice_time'] = date('Y-m-d H:i:s'); //通知时间
				$data_notice['user_id'] = $data['teacher_id']; //发布人id
				$student = (new StudentModel())->get($params['student_id']);
				$data_notice['notice_object'] = (new ParentInformationModel())->get(['student_id' => $params['student_id'], 'username' => $student['guardian_phone']])['id'];//通知对象
				$data_notice['notice_name'] = '点评通知'; //通知名称
				if(!$status_comment){
						$data_notice['content'] = '任课老师'.$grades_res['teacher'].'修改了'.$course_name.'点评'; //具体内容
				}else{
						$data_notice['content'] = '任课老师'.$grades_res['teacher'].'点评了'.$course_name; //具体内容
				}
				$data_notice['notice_type'] = 1; //通知方向：1机构端、家长端；2机构端；3家长端
				$data_notice['status'] = 1; //存稿还是发布：1发布 2存稿
				
				Db::name('edu_my_notice')->insert($data_notice);  //插入通知表
				$notice_id = Db::name('edu_my_notice')->getLastInsID();
				$item = [];
                $item['notice_id'] = $notice_id;
                $item['notice_object_id'] = $data_notice['notice_object'];
				Db::name('edu_my_notice_object')->insert($item);
				
				
			
            $count = (new CommentModel())->where(['cmdl_id' => $params['cmdl_id'], 'student_id' => $params['student_id']])->count();
            if (2 === (int) $count) {
                (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $params['cmdl_id'], 'student_id' => $data['student_id']])->update(['is_comment' => 1]);
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
}
